package com.xindong.zhitgx;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.meihu.beauty.utils.MhDataManager;
import com.xindong.zhitgx.factory.XinDongBeautyToolsViewFactory;
import com.xindong.zhitgx.plugins.XinDongFlutterPlugin;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.umlink.MobclickLink;
import com.umeng.umlink.UMLinkListener;

import java.util.HashMap;
import java.util.Objects;

import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
    private static final String channelName = "com.xindong.zhitgx"; // 通道
    private static final String umLinkData = "chaoLianData"; //
    public static MainActivity mainContext;
    public static BinaryMessenger binaryMessenger;
    public static MethodChannel methodChannel;

    public SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainContext = this;

        sharedPreferences = mainContext.getSharedPreferences("XINDONG_PREFERENCE", Context.MODE_PRIVATE);

        // 友盟
        initUM();
        // 美颜初始化
        MhDataManager.getInstance().create(mainContext);

        // 通信通道
        binaryMessenger = Objects.requireNonNull(getFlutterEngine()).getDartExecutor();
        methodChannel = new MethodChannel(binaryMessenger, channelName);
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        // 注册插件的实例(如果有多个需要册插件的实例，依次增加即可)
        flutterEngine.getPlugins().add(new XinDongFlutterPlugin());

        BinaryMessenger binaryMessenger = Objects.requireNonNull(getFlutterEngine()).getDartExecutor().getBinaryMessenger();
        // 注册PlatformViewFactory
        flutterEngine.getPlatformViewsController().getRegistry().registerViewFactory(
                "xindong_beauty_tools", new XinDongBeautyToolsViewFactory(binaryMessenger)
        );
    }

    // 默认渠道
    public static String getDefaultChannel(Context context) {
        String resultData = "android";
        try {
            //注意此处为ApplicationInfo，因为友盟设置的meta-data是在application标签中
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo != null) {
                if (applicationInfo.metaData != null) {
                    //key要与manifest中的配置文件标识一致
                    Object value = applicationInfo.metaData.get("channel");
                    if (value != null) {
                        resultData = value.toString();
                        Log.e("默认渠道----", resultData);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return resultData;
    }


    // 友盟预初始化，不是真的初始化
    public void initUM() {
        UMConfigure.preInit(mainContext, "653f116c58a9eb5b0af8e692", MainActivity.getDefaultChannel(mainContext));
        UMConfigure.setLogEnabled(true);
    }

    public void initLink() {
        boolean hasInstallParams = sharedPreferences.getBoolean("keyInstallParams", false);
        if (!hasInstallParams) {
            MobclickLink.getInstallParams(mainContext, umLinkListener);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Uri uri = intent.getData();
        if (uri != null) {
            // 此处要调用，否则App在后台运行时，会无法截获
            MobclickLink.handleUMLinkURI(this, uri, umLinkListener);
        }
    }

    UMLinkListener umLinkListener = new UMLinkListener() {
        @Override
        public void onLink(String path, HashMap<String, String> params) {
            // 不调整页面不管path，只拿参数params
            methodChannel.invokeMethod(umLinkData, params);
        }

        @Override
        public void onInstall(HashMap<String, String> install_params, Uri uri) {
            if (install_params.isEmpty() && uri.toString().isEmpty()) {
            } else {
                if (!install_params.isEmpty()) {
                    //此处获得install_params即为配置的新装参数kv键值对
                }
                if (!uri.toString().isEmpty()) {
                    //可将uri交给handleUMLinkURI处理，回调至onLink
                    MobclickLink.handleUMLinkURI(mainContext, uri, umLinkListener);
                }
            }
            methodChannel.invokeMethod(umLinkData, install_params);
            SharedPreferences.Editor spEditor = sharedPreferences.edit();
            spEditor.putBoolean("keyInstallParams", true);
            spEditor.apply();
        }

        @Override
        public void onError(String error) {
            Log.e("UMLink", "网络异常" + error.toString());
        }
    };
}
